package com.transcendence.appwidget.twofive;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jinrishici.sdk.android.JinrishiciClient;
import com.jinrishici.sdk.android.listener.JinrishiciCallback;
import com.jinrishici.sdk.android.model.JinrishiciRuntimeException;
import com.jinrishici.sdk.android.model.PoetySentence;
import com.transcendence.appwidget.R;
import com.transcendence.appwidget.WidgetUpdateListener;
import com.transcendence.appwidget.activity.HotActivity;
import com.transcendence.appwidget.activity.MainActivity;
import com.transcendence.appwidget.activity.SignActivity;
import com.transcendence.core.global.CORE;
import com.transcendence.core.global.Global;
import com.transcendence.core.utils.date.DateUtils;
import com.transcendence.core.utils.glide.GlideUtils;
import com.transcendence.core.utils.log.LogUtils;
import com.transcendence.core.utils.sp.SPUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author joephone
 * @date 2023/9/12
 * @desc
 */
public class TwoFiveAppWidget extends AppWidgetProvider {

    private static final int MAX_SIZE = 3;
    private final List<String> mCache = new ArrayList<>(MAX_SIZE);

    private static final int UPDATE = 0x123;
    private Context mContext;
    private AppWidgetManager mAppWidgetManager;
    private int[] mAppWidgetIds;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE:
                    // 更新UI
                    updateText();
                    break;
            }
        }
    };

    /**
     * 每次窗口小部件被更新都调用一次该方法（创建、时间到更新周期都会调起这里）
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        mContext = context;
        mAppWidgetManager = appWidgetManager;
        mAppWidgetIds = appWidgetIds;
        LogUtils.d("TwoFiveAppWidget onUpdate");
        //更新数据   UUID.randomUUID().toString()
        updateWidgetView();
//         RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget_5_2);

    }

    /**
     * 接收窗口小部件点击时发送的广播
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        LogUtils.d("TwoFiveAppWidget onReceive");
        if(intent!=null && !TextUtils.isEmpty(intent.getAction())){
            switch (intent.getAction()){
                case Global.REFRESH_CLICK_ACTION:
                    LogUtils.d("onReceive REFRESH_CLICK_ACTION");
                    request(context);
                    break;
                case Global.REFRESH_LOGIN:
                    LogUtils.d("onReceive REFRESH_LOGIN 收到通知，更新小部件");
//                    request(context);
                    updateWidgetView();
                    break;
            }
        }
    }

    /**
     * 每删除一次窗口小部件就调用一次
     */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    /**
     * 当最后一个该窗口小部件删除时调用该方法
     */
    @Override

    public void onDisabled(Context context) {
        super.onDisabled(context);
        LogUtils.d("TwoFiveAppWidget onDisabled");
    }

    /**
     * 当该窗口小部件第一次添加到桌面时调用该方法
     */
    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        LogUtils.d("TwoFiveAppWidget onEnabled");
    }

    /**
     * 当小部件大小改变时
     */
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    }

    /**
     * 当小部件从备份恢复时调用该方法
     */
    @Override
    public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
        super.onRestored(context, oldWidgetIds, newWidgetIds);
        LogUtils.e("当小部件从备份恢复时调用该方法");
    }

    /**
     * 更新桌面小组件数据用，APP中也可以在任意地方传入任意数据进来主动更新小组件数据
     */
    public void updateWidgetView() {
        LogUtils.d("updateWidgetView");
        //初始化RemoteViews
        RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_five);

        views.setViewVisibility(
                R.id.iv_ad,
                View.INVISIBLE
        );

        views.setViewVisibility(
                R.id.ll_mid_login_nocar,
                View.GONE
        );
        views.setViewVisibility(
                R.id.rl_mid_login_normal,
                View.GONE
        );

//        views.setOnClickPendingIntent(
//                R.id.tv_edit,
//                registerEditAction(context)
//        );

        // 设置按钮点击事件
        views.setOnClickPendingIntent(
                R.id.tv_edit,
                registerRefreshAction(mContext)
        );

        isShowUnLoginBottom(views,View.GONE);

        isShowLoginNormalBottom(views,View.GONE);

        isShowLoginChangeBottom(views,View.GONE);

        isShowLoginUnableControlBottom(views,View.GONE);

        isShowLoginMidLayout(views,View.GONE);

        isShowChargeLayout(views,mContext,View.INVISIBLE);

        isShowUserLayout(views,View.INVISIBLE);

        switch (CORE.CAR_CONTROL_STATE_CURRENT){
            case UNLOGIN:
                isShowUnLoginBottom(views,View.VISIBLE);
                isShowUnLoginMidLayout(views,mContext,mAppWidgetIds);
                break;
            case LOGIN_NOCAR:
                showLoginNocarLayout(views,mContext);
                isShowUserLayout(views,View.VISIBLE);
                break;
            case LOGIN_NORMAL:
                isShowLoginMidLayout(views,View.VISIBLE);
                isShowLoginNormalBottom(views,View.VISIBLE);
                break;
            case LOGIN_UNCONTROL:
                isShowLoginMidLayout(views,View.VISIBLE);
                isShowLoginUnableControlBottom(views,View.VISIBLE);
                break;
            case LOGIN_CHANGING:
                isShowChargeLayout(views,mContext,View.VISIBLE);
                isShowLoginMidLayout(views,View.VISIBLE);
                isShowLoginChangeBottom(views,View.VISIBLE);
                break;
        }


        for (int appWidgetId : mAppWidgetIds) {
            mAppWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }




    private void updateRemoteViewImage(RemoteViews remoteViews, ComponentName componentName, Context context) {
        int resourceId = R.drawable.bg_app_widget_gradient_default;
        int selected = SPUtils.getInstance().getInt("AppWidgetBgSelected",0);
        switch (selected){
            case 0:
                resourceId = R.drawable.bg_app_widget_gradient_default;
                break;
            case 1:
                resourceId = R.drawable.bg_app_widget_gradient_one;
                break;
            case 2:
                resourceId = R.drawable.bg_app_widget_gradient_two;
                break;
            case 3:
                resourceId = R.drawable.bg_app_widget_gradient_three;
                break;
            case 4:
                resourceId = R.drawable.bg_app_widget_gradient_four;
                break;
        }
        remoteViews.setImageViewResource(
                R.id.bg_appwidget,
                resourceId
        );
        AppWidgetManager.getInstance(context)
                .updateAppWidget(componentName, remoteViews);
    }

    private PendingIntent registerDateAction(Context context) {
        Intent intent = new Intent(context,MainActivity.class);
        intent.putExtra("path","date");
        Bundle bundle = new Bundle();
        bundle.putString("appWidgetPath","date");
        intent.putExtras(bundle);
        return PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT,bundle);
    }

    private PendingIntent registerHotAction(Context context) {
        Intent intent = new Intent(context,HotActivity.class);
        intent.putExtra("path","hot");
        Bundle bundle = new Bundle();
        bundle.putString("appWidgetPath","hot");
        intent.putExtras(bundle);
        return PendingIntent.getActivity(context,1,intent,PendingIntent.FLAG_UPDATE_CURRENT,bundle);
    }

    private PendingIntent registerSignAction(Context context) {
        Intent intent = new Intent(context,SignActivity.class);
        intent.putExtra("path","sign");
        Bundle bundle = new Bundle();
        bundle.putString("appWidgetPath","sign");
        intent.putExtras(bundle);
        return PendingIntent.getActivity(context,2,intent,PendingIntent.FLAG_UPDATE_CURRENT,bundle);
    }

//    private PendingIntent registerEditAction(Context context) {
////        SPUtils.getInstance().save("goto_edit",true);
////        boolean flag = SPUtils.getInstance().get("goto_edit",false);
////        LogUtils.d("registerEditAction :"+flag);
//        Toast.makeText(context,"edit",Toast.LENGTH_SHORT).show();
//        Intent intent = new Intent(context, EditActivity.class);
//        intent.putExtra("path","edit");
//        Bundle bundle = new Bundle();
//        bundle.putString("appWidgetPath","edit");
//        intent.putExtras(bundle);
//        return PendingIntent.getActivity(context,3,intent,PendingIntent.FLAG_UPDATE_CURRENT,bundle);
//    }

    private PendingIntent registerRefreshAction(Context context) {
        //注册广播
        Intent intent = new Intent(Global.REFRESH_CLICK_ACTION);
        ComponentName componentName = new ComponentName(context,TwoFiveAppWidget.class);
        intent.setComponent(componentName);

        return PendingIntent.getBroadcast(
                context,
                R.id.tv_edit,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
    }

    private void request(Context context) {
        mContext = context;
        LogUtils.d("TwoFiveAppWidget---------------request---------------今日诗词");
        JinrishiciClient client = JinrishiciClient.getInstance();
        client.getOneSentenceBackground(new JinrishiciCallback() {
            @Override
            public void done(PoetySentence data) {
                LogUtils.d("今日诗词---------------"+data.getData().getContent());
                mCache.add(data.getData().getContent());
                sendMsgUpdateUI();
            }

            @Override
            public void error(JinrishiciRuntimeException e) {
                LogUtils.d("error: code = " + e.getCode() + " message = " + e.getMessage());
            }
        });
    }

    private void sendMsgUpdateUI() {
        Message msg = mHandler.obtainMessage();
        msg.what = UPDATE;
        mHandler.sendMessage(msg);
    }


    public String getShici() {
        if (mCache.isEmpty()) {
            return null;
        }
        return mCache.get(0);
    }

    private void updateText() {
        LogUtils.d("更新UI");
        RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_five);
        remoteViews.setTextViewText(R.id.tv_name_car,getShici());

        remoteViews.setTextViewText(R.id.tv_date_time,getDateTime());
        String url = "https://app-lcbqiniu.dfpv.com.cn/Fp0NJYFOZix54ly7vGbG7LpHt-QS";


        Glide.with(mContext.getApplicationContext())
                .asBitmap()
                .load("https://app-lcbqiniu.dfpv.com.cn/Fp0NJYFOZix54ly7vGbG7LpHt-QS")
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.layout_two_five);
                        remoteViews.setImageViewBitmap(R.id.iv_ad,getRoundedCornerBitmap(resource,20));   //getRoundedCornerBitmap(resource,80)
                        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
                        ComponentName appWidgetIds = new ComponentName(mContext, TwoFiveAppWidget.class);
                        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        // Handle cleanup here
                    }
                });


        AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
        ComponentName componentName = new ComponentName(mContext, TwoFiveAppWidget.class);
        manager.updateAppWidget(componentName,remoteViews);
    }

    private String getDateTime(){
        return DateUtils.getInstance().formatDate12String(System.currentTimeMillis()+"");
    }


    private void isShowUnLoginBottom(RemoteViews views,int state){
        views.setViewVisibility(
                R.id.ll_bottom_unlogin,
                state
        );
    }

    private void isShowLoginNormalBottom(RemoteViews views,int state){
        views.setViewVisibility(
                R.id.ll_bottom_login_normal,
                state
        );
    }

    private void isShowLoginChangeBottom(RemoteViews views,int state){
        views.setViewVisibility(
                R.id.ll_bottom_normal_charge,
                state
        );
    }

    private void isShowLoginUnableControlBottom(RemoteViews views,int state){
        views.setViewVisibility(
                R.id.tv_bottom_unable_control,
                state
        );
    }


    private void isShowLoginMidLayout(RemoteViews views,int state){
        views.setViewVisibility(
                R.id.rl_mid_login_normal,
                state
        );
        views.setViewVisibility(
                R.id.tv_date_time,
                View.VISIBLE
        );
        views.setTextViewText(
                R.id.tv_date_time,
                getDateTime()
        );
        views.setViewVisibility(
                R.id.rl_mid_login_normal,
                View.VISIBLE
        );
        views.setViewVisibility(
                R.id.ll_mid_login_nocar,
                View.GONE
        );
        views.setProgressBar(R.id.oil_progress_bar,
                100,
                16,
                false);
        views.setTextViewText(
                R.id.tv_pb_oil,
                16+"%");
    }

    private void isShowUnLoginMidLayout(RemoteViews views,Context context, int[] appWidgetIds){
        views.setViewVisibility(
                R.id.tv_name_car,
                View.GONE
        );
        views.setViewVisibility(
                R.id.tv_name_user,
                View.GONE
        );
        views.setViewVisibility(
                R.id.tv_date_time,
                View.INVISIBLE
        );
        views.setViewVisibility(
                R.id.ll_date,
                View.INVISIBLE
        );
        views.setViewVisibility(
                R.id.ll_shop,
                View.INVISIBLE
        );
        views.setViewVisibility(
                R.id.ll_sign,
                View.INVISIBLE
        );
        views.setViewVisibility(
                R.id.rl_mid_login_normal,
                View.GONE
        );

        views.setViewVisibility(
                R.id.iv_ad,
                View.VISIBLE
        );
////                views.setOnClickPendingIntent(
////                        R.id.iv_ad,
////                        registerDateAction(context)
////                );
//        Glide.with(context.getApplicationContext())
//                .asBitmap()
//                .load("https://app-lcbqiniu.dfpv.com.cn/Fp0NJYFOZix54ly7vGbG7LpHt-QS")
//                .into(new CustomTarget<Bitmap>() {
//                    @Override
//                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.layout_two_five);
//                        remoteViews.setImageViewBitmap(R.id.iv_ad, resource);
//                        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
//                        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
//                    }
//
//                    @Override
//                    public void onLoadCleared(@Nullable Drawable placeholder) {
//                        // Handle cleanup here
//                    }
//                });
    }

    private void showLoginNocarLayout(RemoteViews views, Context context) {


        views.setViewVisibility(
                R.id.tv_date_time,
                View.INVISIBLE
        );
        views.setViewVisibility(
                R.id.ll_mid_login_nocar,
                View.VISIBLE
        );
        views.setViewVisibility(
                R.id.rl_mid_login_normal,
                View.GONE
        );
        //注册点击事件
        views.setOnClickPendingIntent(
                R.id.ll_date,
                registerDateAction(context)
        );
        views.setOnClickPendingIntent(
                R.id.ll_shop,
                registerHotAction(context)
        );
        views.setOnClickPendingIntent(
                R.id.ll_sign,
                registerSignAction(context)
        );
    }


    private void isShowChargeLayout(RemoteViews views, Context context,int state) {
        views.setViewVisibility(
                R.id.iv_charge,
                state
        );
        views.setViewVisibility(
                R.id.tv_charge,
                state
        );
    }


    private void isShowUserLayout(RemoteViews views,int state) {
        views.setViewVisibility(
                R.id.tv_name_car,
                View.VISIBLE
        );
        if(state == View.VISIBLE){
            views.setTextViewText(
                    R.id.tv_name_user,
                    "用户"
            );
        }

    }


    public Bitmap getRoundedCornerBitmap(Bitmap bitmap,int radius) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        paint.setShader(shader);
        canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
        return output;
    }


}
